using Godot;

public partial class Tower : Area2D
{
    [Export] private float _mAttackRange = 200.0f; // 攻击范围
    [Export] private float _mAttackInterval = 1.0f; // 攻击间隔(秒)
    [Export] private int _mDamage = 10; // 攻击力
    [Export] private PackedScene _mBulletScene; // 子弹场景
    [Export] private Node2D _mBulletGeneratePos; // 子弹生成位置

    private Timer _mAttackTimer; // 攻击计时器
    private TargetSearcher _mTargetSearcher; // 目标搜索器
    private Node2D _mTarget; // 当前目标
    private bool _mIsActive = true; // 是否激活

    private Vector2 BulletPos => _mBulletGeneratePos.GlobalPosition;

    public override void _Ready()
    {
        base._Ready();

        // 初始化攻击计时器
        _mAttackTimer = new Timer();
        _mAttackTimer.WaitTime = _mAttackInterval;
        _mAttackTimer.Timeout += OnAttackTimerTimeout;
        AddChild(_mAttackTimer);
        _mTargetSearcher = GetNode<TargetSearcher>("TargetSearcher");

        // 只有正确放置后才开始攻击
        if (_mIsActive)
        {
            _mAttackTimer.Start();
        }
    }

    public override void _Process(double delta)
    {
    }

    // 检查是否可以放置在指定位置
    private bool CanPlaceAt(Vector2 position, Node2D slot)
    {
        // 这里可以添加槽位检查逻辑
        _mIsActive = true;
        GlobalPosition = position;
        return true;
    }

    // 攻击计时器超时，发射子弹
    private void OnAttackTimerTimeout()
    {
        // 修正条件判断顺序
        if (!IsTargetValid())
        {
            FindTarget();
        }

        if (IsTargetValid() && _mBulletScene != null)
        {
            FireBullet();
        }
    }

    // 发射子弹
    private void FireBullet()
    {
        // 反转判断条件：当目标有效时才发射
        if (!IsTargetValid() || _mBulletScene == null)
        {
            Logger.SError($"{_mTarget}:Bullet scene is not set!");
            return;
        }

        // 保持原有发射逻辑...
        TowerLookAt(_mTarget.GlobalPosition);
        var bullet = _mBulletScene.Instantiate<Node2D>();

        // 设置子弹属性
        if (bullet is Bullet bulletNode)
        {
            bulletNode.StartPosition = BulletPos;
            bulletNode.Target = _mTarget;
            // 第7行已为int类型
            bulletNode.Damage = _mDamage;
        }

        GetParent().AddChild(bullet);
    }

    // 寻找范围内的目标
    private void FindTarget()
    {
        var target = _mTargetSearcher.GetTarget();
        if (target != null)
        {
            _mTarget = target;
            TowerLookAt(_mTarget.GlobalPosition);
        }

    }

    // Tower 转动
    private void TowerLookAt(Vector2 targetPosition)
    {
        var angle = Position.AngleToPoint(targetPosition);
        // 用一个快速tween实现平滑转动，并且保证总是最小角度
        var tween = CreateTween().SetEase(Tween.EaseType.In).SetTrans(Tween.TransitionType.Sine);
        tween.TweenProperty(this, "rotation", angle, 0.1);
    }

    private bool IsTargetValid()
    {
        if (_mTarget == null || _mTargetSearcher == null || !IsInstanceValid(_mTarget))
        {
            return false;
        }

        // 如果目标不在攻击范围内，返回false
        return _mTargetSearcher.IsTargetInRange(_mTarget);
    }

}
